import os
import secrets

import redis as redis
from environs import Env
from pathlib import Path

from pydantic import BaseSettings

env = Env()
root_path = Path(__file__).resolve(strict=True).parent.parent.parent
if os.path.exists(f"{root_path}/.env"):
    env.read_env(f"{root_path}/.env")

# BASE_PATH = Path(__file__).resolve(strict=True).parent.parent


class Settings(BaseSettings):
    ENV: str = env.str("ENV", "local")
    ADD_EXCEPTION_HANDLERS: bool = env.bool("ADD_EXCEPTION_HANDLERS", True)
    DOMAIN: str = env.str("DOMAIN", "http://localhost:8000/")

    MYSQL_USER: str = env.str("MYSQL_USER", None)
    MYSQL_PASSWORD: str = env.str("MYSQL_PASSWORD", None)
    MYSQL_HOST: str = env.str("MYSQL_HOST", None)
    MYSQL_PORT: str = env.str("MYSQL_PORT", None)
    MYSQL_DATABASE: str = env.str("MYSQL_DATABASE", None)
    DATABASE_URL: str = env.str("DATABASE_URL",
                                f'mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}')

    # openai
    OPENAI_ORGANIZATION: str = env.str("OPENAI_ORGANIZATION", None)
    OPENAI_API_KEY: str = env.str("OPENAI_API_KEY", None)

    # jwt
    SECRET_KEY: str = env.str("SECRET_KEY", None)
    ALGORITHM: str = env.str("ALGORITHM", "HS256")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = env.int("ACCESS_TOKEN_EXPIRE_MINUTES", 1440)

    # redis
    REDIS_URL: str = env.str("REDIS_URL", None)

    # free count
    FREE_COUNT: int = env.int("FREE_COUNT", 2)
    FREE_ACCOUNT_COUNT: int = env.int("FREE_ACCOUNT_COUNT", 3)
    RESET_FREE_TIME: int = env.int("RESET_FREE_COUNT", 86400)

    # email
    EMAIL_SERVICE: str = env.str("EMAIL_SERVICE", "smtp.exmail.qq.com")
    EMAIL_PORT: int = env.int("EMAIL_PORT", 465)
    EMAIL_ADDRESS: str = env.str("EMAIL_ADDRESS", "hello@open-app.club")
    EMAIL_PASSWORD: str = env.str("EMAIL_PASSWORD", "MkTEbCoQpHansSwc")

    # hupijiao
    HUPIJIAO_URL: str = env.str("HUPIJIAO_URL", "https://api.xunhupay.com/payment/do.html")
    HUPIJIAO_APP_ID: str = env.str("HUPIJIAO_APP_ID", None)
    HUPIJIAO_APP_SECRET: str = env.str("HUPIJIAO_APP_SECRET", None)

    # cors
    ORIGINS = ["*"]

    class Config:
        case_sensitive = True


settings = Settings()

TORTOISE_ORM = {
                'connections': {
                    # Dict format for connection
                    'default': settings.DATABASE_URL,
                    # Using a DB_URL string
                },
                'apps': {
                    'models': {
                        'models': ['models', "aerich.models"],
                        # If no default_connection specified, defaults to 'default'
                        'default_connection': 'default',
                    }
                }
            }


POOL = redis.ConnectionPool().from_url(settings.REDIS_URL)
REDIS_CLIENT = redis.Redis(connection_pool=POOL)